Test mail

This file you can find several mail example. that i tried.


In [ ]:
#!/usr/bin/python
__author__ = 'Shahariar'
import email
import imaplib
import ctypes
import getpass
from playsound import playsound
# ORG_EMAIL = "@gmail.com"
# FROM_EMAIL = "youser mail" + ORG_EMAIL
# FROM_PWD = "pass"

In [ ]:
mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
FROM_EMAIL = raw_input("insert Email : ")
#pwd = raw_input("insert password : ")
FROM_PWD = getpass.getpass("input : ")
mail.login(FROM_EMAIL, FROM_PWD)
mail.select("INBOX")

In [ ]:
def read_email_from_gmail():
    try:
        type, data = mail.search(None, 'ALL')
        mail_ids = data[0]

        id_list = mail_ids.split()
        first_email_id = int(id_list[0])
        latest_email_id = int(id_list[-1])

        #parser = Parser()
        for i in range(latest_email_id, latest_email_id - 10, -1):
            typ, data = mail.fetch(i, '(RFC822)')

            for response_part in data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_string(response_part[1])
                    email_subject = msg['subject']
                    email_from = msg['from']

                    print 'From : ' + email_from
                    print 'Subject : ' + email_subject
                    print "Read mail: https://gmail.com\n"

    except Exception, e:
        print (str(e))

In [ ]:
def loop():
    mail.select("INBOX")
    n = 0
    (retcode, messages) = mail.search(None, '(UNSEEN)')
    if retcode == 'OK':

        for num in messages[0].split():
            # print 'Processing '
            n = n + 1
            print n
            typ, data = mail.fetch(num, '(RFC822)')
            for response_part in data:
                if isinstance(response_part, tuple):
                    original = email.message_from_string(response_part[1])
                    print original['From']
                    data = original['Subject']
                    #print original['Body']
                    playsound('demonstrative.wav')
                    print data
                    print "Read mail: https://gmail.com"
                    if data == 'eject':
                        ctypes.windll.WINMM.mciSendStringW(u"set cdaudio door open", None, 0, None)
                    typ, data = mail.store(num, '+FLAGS', '\\Seen')

    from sys import stdout
    stdout.write(str('#'))

In [ ]:
if __name__ == '__main__':
    try:
        ##print 'Press Ctrl-C to quit.'
        loop()
    finally:
        print"thanks"

In [ ]:
import smtplib

sender = FROM_EMAIL
receivers = FROM_EMAIL

message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except:
   print "Error: unable to send email"

In [ ]:
import smtplib
to = FROM_EMAIL
gmail_user = FROM_EMAIL
gmail_pwd = FROM_PWD
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)

In [ ]:
#! /usr/bin/python
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr


# me == my email address
# you == recipient's email address
me = FROM_EMAIL
you = 'reciver mail @mail.com'

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Hello Nasty Boy"
msg['From'] = formataddr((str(Header('Shahariar Azad Rabby', 'utf-8')), FROM_EMAIL))
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\n5633222222222222222http://www.python.org"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       
       Here is the <a href="http://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""

html = x
#attach = 'mail.txt'
# Record the MIME types of both parts - text/plain and text/html.
#part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
#msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
#s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
smtpserver.sendmail(me, you, msg.as_string())
smtpserver.quit()